package cn.dlc.com.filter;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 邓立川
 * @date 2021/1/7 16:00
 * @desc 针对filter的限流的类
 */
@Configuration
public class KeyResolverConfiguration {

    /**
     * 配置限流规则
     * @return
     */
    @Bean(name = "pathKeyResolver")
    public KeyResolver pathKeyResolver(){
        return new KeyResolver() {
            /**
             * Mono是Spring WebFlux里面的一个新的类型，可以认为是异步请求，减少阻塞
             * @param exchange
             * @return
             */
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                // 拿到路径，基于请求路径的限流，访问这个路劲会受到配置文件中的流量控制
                System.out.println("这个地方......");

                System.out.println(": " + exchange.getRequest().getPath().toString());

                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }

    // 这几个KeyResolver不能同时存在

//    @Bean
    public KeyResolver paramKeyResolver(){

        return new KeyResolver() {
            // 有这个参数的时候限流
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest()
                        .getQueryParams().getFirst("userid").toString());
            }
        };
    }

//    @Bean
    public KeyResolver ipKeyResolver(){

        return new KeyResolver() {
            // ip限流
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                // ip限流
                 return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
            }
        };
    }

}
